<template>
  <div class="login-account">
    <el-form
      :model="account"
      status-icon
      :rules="rules"
      ref="formRef"
      label-width="60px"
    >
      <el-form-item label="账号" prop="name">
        <el-input v-model="account.name"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="account.password" show-password></el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref } from 'vue'
import { useStore } from 'vuex'

import { rules } from '../config/account-config-rules'
import localCache from '@/utils/cache'
import { ElForm } from 'element-plus'

export default defineComponent({
  setup() {
    const store = useStore()

    const account = reactive({
      name: localCache.getCache('name') ?? '',
      password: localCache.getCache('passwd') ?? ''
    })

    const formRef = ref<InstanceType<typeof ElForm>>()

    const loginAction = (isKeepPassword: boolean) => {
      // console.log('点击了登陆,触发account的登陆~')
      formRef.value?.validate((valid) => {
        // console.log(valid)
        if (valid) {
          // console.log('验证通过执行真正的登陆逻辑')
          // 1 判断是否需要记住密码
          if (isKeepPassword) {
            // 本地缓存 local sotre,session store
            localCache.setCache('name', account.name)
            localCache.setCache('passwd', account.password)
          } else {
            localCache.deleteCache('name')
            localCache.deleteCache('passwd')
          }
          // 2 执行登陆验证
          store.dispatch('loginModule/accountLoginAction', { ...account })
        }
      })
    }

    return {
      account,
      rules,
      loginAction,
      formRef
    }
  }
})
</script>

<style scoped></style>
